package com.probiz.estore.catalog.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.probiz.estore.Constants;
import com.probiz.estore.catalog.dao.GiftCategoryDao;
import com.probiz.estore.catalog.model.GiftCategoryFullyModel;
import com.probiz.estore.catalog.service.GiftCategoryManager;
import com.probiz.estore.catalog.util.CatalogCodeGenerator;
import com.probiz.estore.common.model.catalog.GiftCategory;
import com.probiz.estore.core.util.I18nUtil;
import com.probiz.estore.sales.dao.GiftDao;

/**
 * Manager implementation for GiftCategory, responsible for business processing,
 * and communicate between web and persistence layer.
 */
public class GiftCategoryManagerImpl extends BaseCategoryManagerImpl<GiftCategory> implements GiftCategoryManager {
	private GiftCategoryDao	giftCategoryDao	= null;
	private GiftDao			giftDao			= null;

	/**
	 * @param giftCategoryDao
	 *            the giftCategoryDao to set
	 */
	public void setGiftCategoryDao(GiftCategoryDao giftCategoryDao) {
		this.giftCategoryDao = giftCategoryDao;
	}

	public void setGiftDao(GiftDao giftDao) {
		this.giftDao = giftDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.catalog.service.impl.BaseCategoryManagerImpl#initManager()
	 */
	@Override
	protected void initManager() {
		dao = giftCategoryDao;
		categoryDao = giftCategoryDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.catalog.service.impl.BaseCategoryManagerImpl#preDelete(java.lang.Object)
	 */
	@Override
	protected void preDelete(GiftCategory entity) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.catalog.service.impl.BaseCategoryManagerImpl#preSave(java.lang.Object)
	 */
	@Override
	protected void preSave(GiftCategory entity) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.catalog.service.GiftCategoryManager#deleteFully(com.probiz.estore.common.model.catalog.GiftCategory)
	 */
	public Map<String, Object> deleteFully(GiftCategory category) {
		Map<String, Object> returnMsgs = new HashMap<String, Object>();

		returnMsgs.put("categoryId", category.getCategoryId());
		if (category.getCategoryId() == 1) {
			// case:如果是根目录
			returnMsgs.put("result", -1);
			returnMsgs.put("message", I18nUtil.getInstance().getMessage(
					"giftCategory.del.root"));
		} else if (!giftDao.countGiftByCategoryId(category.getCategoryId())
				.equals(new Integer("0"))) {
			// case:如果包含礼品
			returnMsgs.put("result", -3);
			returnMsgs.put("message", I18nUtil.getInstance().getMessage(
					"giftCategory.del.containGift"));
		} else {
			List<GiftCategory> giftCategorys = giftCategoryDao.getCategorysByCategoryPath(category.getCategoryPath());
	        boolean flag = false;
	        for (GiftCategory gc: giftCategorys) {
	        	Integer pcont = giftDao.countGiftByCategoryId(gc.getCategoryId());
	        	if (!pcont.equals(new Integer("0"))) {
	        		flag = true;
	        		break;
	        	}
	        }
	        //子目录有礼品不能删除
	        if (flag) {
				returnMsgs.put("result", -3);
				returnMsgs.put("message",I18nUtil.getInstance().getMessage("giftCategory.del.containGift"));
	        } else {
				// otherwise:成功删除
	
				// 获得父id
				Integer parentId = category.getParentId();
				GiftCategory parent = giftCategoryDao.getById(category
						.getParentId());
				Integer subCategoryCount = giftCategoryDao
						.countSubCategoryById(parent.getCategoryId());
				if (subCategoryCount.compareTo(new Integer("1")) <= 0) {
					parent.setHasChildren(Constants.FLAG_FALSE);
					giftCategoryDao.save(parent);
				}
				giftCategoryDao.delete(category);
				returnMsgs.put("result", 1);
				returnMsgs.put("message", I18nUtil.getInstance().getMessage(
						"giftCategory.del.success"));
				returnMsgs.put("parentId", parentId);
			}
		}

		return returnMsgs;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.catalog.service.GiftCategoryManager#getCategoryByCode(java.lang.String)
	 */
	public GiftCategory getCategoryByCode(String categoryCode) {
		return giftCategoryDao.getCategoryByCode(categoryCode);
	}

	/*
	 * 
	 */
	public List<GiftCategory> getCategoryByName(String name) {
		return giftCategoryDao.listByProperty("categoryName", name);
	}

	/*
	 * 
	 */
	public Long getSizeByCategoryCodeByNotCategoryId(String categoryCode,
			Integer categoryId) {
		return giftCategoryDao.getSizeByCategoryCodeByNotCategoryId(
				categoryCode, categoryId);
	}

	/*
	 * 
	 */
	public List<GiftCategory> listCategoryByParentIdAndName(
			Integer parentCategoryId, String categoryName) {
		return giftCategoryDao.listCategoryByParentIdAndName(parentCategoryId,
				categoryName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.catalog.service.GiftCategoryManager#saveFully(com.probiz.estore.catalog.model.GiftCategoryFullyModel)
	 */
	public Map<String, Object> saveFully(GiftCategoryFullyModel model) {
		Map<String, Object> returnMsgs = new HashMap<String, Object>();
		// start:主体保存
		GiftCategory category = model.getGiftCategory();

		// start:设置目录编码并检查
		if (StringUtils.isBlank(category.getCategoryCode())) {
			boolean isCodeAvailable = false;
			do {
				String code = CatalogCodeGenerator.generateCode();
				Long size = giftCategoryDao
						.getSizeByCategoryCodeByNotCategoryId(code, category
								.getCategoryId());
				if (size == 0) {
					// 该编码可用
					isCodeAvailable = true;
					category.setCategoryCode(code);
				}
			} while (!isCodeAvailable);
		} else {
			// 用getSizeByCategoryCodeByNotCategoryId而不用getCategoryByCode的原因在于调用后者的时候会有update操作，造成数据库有两个相同code的礼品，出错
			Long size = giftCategoryDao.getSizeByCategoryCodeByNotCategoryId(
					category.getCategoryCode(), category.getCategoryId());

			if (size >= 1) {
				// 编码重复
				returnMsgs.put("error", I18nUtil.getInstance().getMessage(
						"giftCategory.categoryCode.repeated"));
				evict(category); // 必须把evict出session 否则会有update操作
				return returnMsgs;
			}
		}
		// end:设置目录编码并检查

		// start:新增赋值
		if (null == category.getCategoryId()) {
			// case:新增
			GiftCategory parent = giftCategoryDao.getById(category
					.getParentId());
			category.setDepth((short) (parent.getDepth() + 1));
			category.setItemCount(0);
			category.setActiveItemCount(0);
			category.setParentPath(parent.getCategoryPath());
			category.setCategoryPath("");// 临时,必须等categoryId出来后才能再次保存
			category.setHasChildren(Constants.FLAG_FALSE);
			category.setCategoryType((short) 0);
			category.setSortOrder(GiftCategory.SORTORDER_DEFAULT_VALUE);
			// 保存父亲
			parent.setHasChildren(Constants.FLAG_TRUE);
			giftCategoryDao.save(parent);

			giftCategoryDao.save(category);
			// start:保存categoryPath
			category.setCategoryPath(parent.getCategoryPath()
					+ category.getCategoryId() + ".");
			giftCategoryDao.save(category);
			// end:保存categoryPath
		}
		// end:新增赋值

		giftCategoryDao.save(category);
		// end:主体保存

		return returnMsgs;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.catalog.service.GiftCategoryManager#getCategoryIdByUri(java.lang.String)
	 */
	public Integer getCategoryIdByUri(String uri) {
		String categoryId = uri.substring(uri.lastIndexOf("/") + 1, uri
				.lastIndexOf("."));
		if (categoryId.contains("-")) {
			categoryId = categoryId.substring(0, categoryId.indexOf("-"));
		}
		if (categoryId.contains("1L")) {
			categoryId = categoryId.substring("1LCat".length());
		} else {
			categoryId = categoryId.substring("cat".length());
		}
		return Integer.valueOf(categoryId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.catalog.service.GiftCategoryManager#getUriByCategoryId(java.lang.Integer)
	 */
	public String getUriByCategoryId(Integer categoryId) {
		StringBuffer url = new StringBuffer();
		url.append("/gift");
		List<GiftCategory> giftCategoryList = giftCategoryDao
				.getNavigationCategories(categoryId);
		for (GiftCategory giftCategory : giftCategoryList) {
			url.append("-");
			url.append(giftCategory.getCategoryCode());
		}
		url.append("/cat");
		url.append(categoryId.toString());
		url.append(".html");
		return url.toString();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.catalog.service.GiftCategoryManager#getNavigationCategories(java.lang.Integer)
	 */
	public List<GiftCategory> getNavigationCategories(Integer categoryId) {
		return giftCategoryDao.getNavigationCategories(categoryId);
	}

}
